{% extends "base.html" %}

{% block title %}图片编辑工具 - 工具箱{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <h1 class="text-3xl font-bold mb-4">图片编辑工具</h1>
    <p class="text-gray-600 mb-6">基础图片编辑功能，支持裁剪、调整大小、旋转等操作。</p>
    
    <!-- 错误信息显示 -->
    {% if error %}
    <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-6" role="alert">
        <strong class="font-bold">处理失败：</strong>
        <span class="block sm:inline">{{ error }}</span>
    </div>
    {% endif %}
    
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- 上传区域 -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-semibold mb-4">上传图片</h2>
            <form method="POST" enctype="multipart/form-data" class="space-y-4">
                <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-500 transition-colors" id="dropArea">
                    <input type="file" name="file" id="fileInput" class="hidden" accept="image/jpeg,image/png,image/gif,image/webp">
                    <label for="fileInput" class="cursor-pointer">
                        <div class="text-gray-500">
                            <i class="fas fa-cloud-upload-alt text-4xl mb-3"></i>
                            <p>点击或拖拽图片到此处上传</p>
                            <p class="text-sm mt-2">支持 JPG, PNG, GIF, WEBP 格式</p>
                        </div>
                    </label>
                    <div id="preview" class="mt-4 hidden">
                        <img id="imagePreview" class="max-h-48 mx-auto" src="" alt="预览图">
                        <p id="fileName" class="mt-2 text-sm text-gray-500"></p>
                    </div>
                </div>
                
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">编辑操作</label>
                    <div class="grid grid-cols-1 sm:grid-cols-3 gap-2">
                        <label class="flex items-center border rounded-md p-2 cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="operation" value="resize" class="mr-2" checked>
                            <span>调整大小</span>
                        </label>
                        <label class="flex items-center border rounded-md p-2 cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="operation" value="crop" class="mr-2">
                            <span>裁剪</span>
                        </label>
                        <label class="flex items-center border rounded-md p-2 cursor-pointer hover:bg-gray-50">
                            <input type="radio" name="operation" value="rotate" class="mr-2">
                            <span>旋转</span>
                        </label>
                    </div>
                </div>
                
                <!-- 调整大小参数 -->
                <div id="resizeParams" class="space-y-3">
                    <div class="flex items-center space-x-4">
                        <div class="w-1/2">
                            <label for="width" class="block text-sm font-medium text-gray-700 mb-1">宽度 (像素)</label>
                            <input type="number" name="width" id="width" min="1" max="5000" class="w-full border border-gray-300 rounded-md px-3 py-2" placeholder="例如: 800">
                        </div>
                        <div class="w-1/2">
                            <label for="height" class="block text-sm font-medium text-gray-700 mb-1">高度 (像素)</label>
                            <input type="number" name="height" id="height" min="1" max="5000" class="w-full border border-gray-300 rounded-md px-3 py-2" placeholder="例如: 600">
                        </div>
                    </div>
                    <div class="flex items-center">
                        <input type="checkbox" id="keepAspectRatio" class="mr-2" checked>
                        <label for="keepAspectRatio" class="text-sm text-gray-700">保持原始比例</label>
                    </div>
                </div>
                
                <!-- 裁剪参数 -->
                <div id="cropParams" class="space-y-3 hidden">
                    <div class="grid grid-cols-2 gap-3">
                        <div>
                            <label for="left" class="block text-sm font-medium text-gray-700 mb-1">左侧 (像素)</label>
                            <input type="number" name="left" id="left" min="0" class="w-full border border-gray-300 rounded-md px-3 py-2" placeholder="例如: 10">
                        </div>
                        <div>
                            <label for="top" class="block text-sm font-medium text-gray-700 mb-1">顶部 (像素)</label>
                            <input type="number" name="top" id="top" min="0" class="w-full border border-gray-300 rounded-md px-3 py-2" placeholder="例如: 10">
                        </div>
                        <div>
                            <label for="right" class="block text-sm font-medium text-gray-700 mb-1">右侧 (像素)</label>
                            <input type="number" name="right" id="right" min="0" class="w-full border border-gray-300 rounded-md px-3 py-2" placeholder="例如: 500">
                        </div>
                        <div>
                            <label for="bottom" class="block text-sm font-medium text-gray-700 mb-1">底部 (像素)</label>
                            <input type="number" name="bottom" id="bottom" min="0" class="w-full border border-gray-300 rounded-md px-3 py-2" placeholder="例如: 400">
                        </div>
                    </div>
                </div>
                
                <!-- 旋转参数 -->
                <div id="rotateParams" class="space-y-3 hidden">
                    <label for="angle" class="block text-sm font-medium text-gray-700 mb-1">旋转角度</label>
                    <div class="flex items-center space-x-2">
                        <button type="button" id="rotate90" class="bg-gray-200 text-gray-700 py-1 px-3 rounded-md hover:bg-gray-300">90°</button>
                        <button type="button" id="rotate180" class="bg-gray-200 text-gray-700 py-1 px-3 rounded-md hover:bg-gray-300">180°</button>
                        <button type="button" id="rotate270" class="bg-gray-200 text-gray-700 py-1 px-3 rounded-md hover:bg-gray-300">270°</button>
                    </div>
                    <input type="range" name="angle" id="angle" min="0" max="360" step="1" value="90" class="w-full">
                    <div class="text-center">
                        <span id="angleValue">90°</span>
                    </div>
                </div>
                
                <div>
                    <button type="submit" class="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 font-medium">
                        应用编辑
                    </button>
                </div>
            </form>
        </div>
        
        <!-- 结果区域 -->
        <div class="bg-white rounded-lg shadow-md p-6">
            <h2 class="text-xl font-semibold mb-4">编辑结果</h2>
            {% if result %}
                <div class="space-y-4">
                    <div class="border rounded-lg p-4">
                        <div class="grid grid-cols-2 gap-4 text-sm text-gray-600">
                            <div>
                                <p><span class="font-medium">原始尺寸:</span> {{ original_dimensions }}</p>
                                <p><span class="font-medium">原始大小:</span> {{ original_size }}</p>
                            </div>
                            <div>
                                <p><span class="font-medium">处理后尺寸:</span> {{ edited_dimensions }}</p>
                                <p><span class="font-medium">处理后大小:</span> {{ edited_size }}</p>
                            </div>
                        </div>
                    </div>
                    
                    <div class="border rounded-lg p-4">
                        <img src="data:image/jpeg;base64,{{ result }}" class="max-w-full mx-auto" alt="编辑后的图片">
                    </div>
                    
                    <div class="flex space-x-2">
                        <a href="data:image/jpeg;base64,{{ result }}" download="edited_image.jpg" class="flex-1 bg-green-600 text-white py-2 px-4 rounded-md hover:bg-green-700 font-medium text-center">
                            <i class="fas fa-download mr-1"></i> 下载图片
                        </a>
                        <button id="copyBtn" class="bg-gray-200 text-gray-700 py-2 px-4 rounded-md hover:bg-gray-300 font-medium">
                            <i class="fas fa-copy mr-1"></i> 复制图片
                        </button>
                    </div>
                </div>
            {% else %}
                <div class="border rounded-lg p-8 text-center text-gray-500">
                    <i class="fas fa-image text-4xl mb-3"></i>
                    <p>编辑后的图片将显示在这里</p>
                    <p class="text-sm mt-2">您可以下载或复制编辑后的图片</p>
                </div>
            {% endif %}
        </div>
    </div>
    
    <!-- 使用提示 -->
    <div class="bg-blue-50 rounded-lg p-6 mt-8">
        <h2 class="text-xl font-semibold text-blue-800 mb-4">编辑工具说明</h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div>
                <h3 class="font-bold text-blue-700 mb-2">调整大小</h3>
                <ul class="space-y-2 text-blue-700">
                    <li class="flex items-start">
                        <i class="fas fa-info-circle text-blue-500 mt-1 mr-2"></i>
                        <span>输入目标宽度和高度来调整图片尺寸</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-info-circle text-blue-500 mt-1 mr-2"></i>
                        <span>勾选"保持原始比例"可以防止图片变形</span>
                    </li>
                </ul>
            </div>
            <div>
                <h3 class="font-bold text-blue-700 mb-2">裁剪</h3>
                <ul class="space-y-2 text-blue-700">
                    <li class="flex items-start">
                        <i class="fas fa-info-circle text-blue-500 mt-1 mr-2"></i>
                        <span>设置裁剪区域的左上角和右下角坐标</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-info-circle text-blue-500 mt-1 mr-2"></i>
                        <span>坐标是相对于原始图片左上角(0,0)计算的</span>
                    </li>
                </ul>
            </div>
            <div>
                <h3 class="font-bold text-blue-700 mb-2">旋转</h3>
                <ul class="space-y-2 text-blue-700">
                    <li class="flex items-start">
                        <i class="fas fa-info-circle text-blue-500 mt-1 mr-2"></i>
                        <span>使用预设按钮快速旋转90°、180°或270°</span>
                    </li>
                    <li class="flex items-start">
                        <i class="fas fa-info-circle text-blue-500 mt-1 mr-2"></i>
                        <span>或使用滑块调整精确的旋转角度</span>
                    </li>
                </ul>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 操作选择
        const operationRadios = document.querySelectorAll('input[name="operation"]');
        const resizeParams = document.getElementById('resizeParams');
        const cropParams = document.getElementById('cropParams');
        const rotateParams = document.getElementById('rotateParams');
        
        function showParams() {
            const operation = document.querySelector('input[name="operation"]:checked').value;
            
            resizeParams.classList.add('hidden');
            cropParams.classList.add('hidden');
            rotateParams.classList.add('hidden');
            
            if (operation === 'resize') {
                resizeParams.classList.remove('hidden');
            } else if (operation === 'crop') {
                cropParams.classList.remove('hidden');
            } else if (operation === 'rotate') {
                rotateParams.classList.remove('hidden');
            }
        }
        
        operationRadios.forEach(radio => {
            radio.addEventListener('change', showParams);
        });
        
        // 默认显示第一个选项的参数
        showParams();
        
        // 角度滑块
        const angleSlider = document.getElementById('angle');
        const angleValue = document.getElementById('angleValue');
        
        angleSlider.addEventListener('input', function() {
            angleValue.textContent = this.value + '°';
        });
        
        // 旋转快捷按钮
        document.getElementById('rotate90').addEventListener('click', function() {
            angleSlider.value = 90;
            angleValue.textContent = '90°';
        });
        
        document.getElementById('rotate180').addEventListener('click', function() {
            angleSlider.value = 180;
            angleValue.textContent = '180°';
        });
        
        document.getElementById('rotate270').addEventListener('click', function() {
            angleSlider.value = 270;
            angleValue.textContent = '270°';
        });
        
        // 保持宽高比
        const widthInput = document.getElementById('width');
        const heightInput = document.getElementById('height');
        const keepAspectRatio = document.getElementById('keepAspectRatio');
        let aspectRatio = 1.33; // 默认宽高比
        
        // 图片预览
        const fileInput = document.getElementById('fileInput');
        const preview = document.getElementById('preview');
        const imagePreview = document.getElementById('imagePreview');
        const fileName = document.getElementById('fileName');
        
        fileInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const file = this.files[0];
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    fileName.textContent = file.name;
                    preview.classList.remove('hidden');
                    
                    // 计算宽高比
                    const img = new Image();
                    img.onload = function() {
                        aspectRatio = img.width / img.height;
                        
                        // 更新裁剪区域的默认值
                        document.getElementById('left').value = 0;
                        document.getElementById('top').value = 0;
                        document.getElementById('right').value = img.width;
                        document.getElementById('bottom').value = img.height;
                        
                        // 更新调整大小的默认值
                        widthInput.value = img.width;
                        heightInput.value = img.height;
                    };
                    img.src = e.target.result;
                }
                reader.readAsDataURL(file);
            }
        });
        
        // 宽度或高度更改时，保持宽高比
        widthInput.addEventListener('change', function() {
            if (keepAspectRatio.checked && this.value > 0) {
                heightInput.value = Math.round(this.value / aspectRatio);
            }
        });
        
        heightInput.addEventListener('change', function() {
            if (keepAspectRatio.checked && this.value > 0) {
                widthInput.value = Math.round(this.value * aspectRatio);
            }
        });
        
        // 拖放上传
        const dropArea = document.getElementById('dropArea');
        
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, preventDefaults, false);
        });
        
        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }
        
        ['dragenter', 'dragover'].forEach(eventName => {
            dropArea.addEventListener(eventName, highlight, false);
        });
        
        ['dragleave', 'drop'].forEach(eventName => {
            dropArea.addEventListener(eventName, unhighlight, false);
        });
        
        function highlight() {
            dropArea.classList.add('border-blue-500');
        }
        
        function unhighlight() {
            dropArea.classList.remove('border-blue-500');
        }
        
        dropArea.addEventListener('drop', handleDrop, false);
        
        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files && files[0]) {
                fileInput.files = files;
                
                const file = files[0];
                const reader = new FileReader();
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    fileName.textContent = file.name;
                    preview.classList.remove('hidden');
                    
                    // 计算宽高比
                    const img = new Image();
                    img.onload = function() {
                        aspectRatio = img.width / img.height;
                        
                        // 更新裁剪区域的默认值
                        document.getElementById('left').value = 0;
                        document.getElementById('top').value = 0;
                        document.getElementById('right').value = img.width;
                        document.getElementById('bottom').value = img.height;
                        
                        // 更新调整大小的默认值
                        widthInput.value = img.width;
                        heightInput.value = img.height;
                    };
                    img.src = e.target.result;
                }
                reader.readAsDataURL(file);
            }
        }
        
        // 复制图片按钮
        const copyBtn = document.getElementById('copyBtn');
        if (copyBtn) {
            copyBtn.addEventListener('click', function() {
                const img = document.querySelector('[alt="编辑后的图片"]');
                if (img) {
                    try {
                        // 创建canvas
                        const canvas = document.createElement('canvas');
                        canvas.width = img.naturalWidth;
                        canvas.height = img.naturalHeight;
                        
                        // 绘制图片到canvas
                        const ctx = canvas.getContext('2d');
                        ctx.drawImage(img, 0, 0);
                        
                        // 将canvas转换为blob
                        canvas.toBlob(function(blob) {
                            try {
                                // 创建ClipboardItem
                                const item = new ClipboardItem({ 'image/png': blob });
                                
                                // 写入剪贴板
                                navigator.clipboard.write([item]).then(function() {
                                    showMessage('图片已复制到剪贴板', 'success');
                                }, function(error) {
                                    showMessage('复制失败: ' + error, 'error');
                                    console.error('复制失败:', error);
                                });
                            } catch (e) {
                                showMessage('复制失败: 您的浏览器不支持此功能', 'error');
                                console.error('复制API错误:', e);
                            }
                        });
                    } catch (e) {
                        showMessage('复制失败: ' + e.message, 'error');
                        console.error('Canvas操作错误:', e);
                    }
                }
            });
        }
        
        // 消息显示函数
        function showMessage(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = type === 'error' 
                ? 'fixed bottom-4 right-4 bg-red-500 text-white px-4 py-2 rounded shadow-lg z-50'
                : 'fixed bottom-4 right-4 bg-green-500 text-white px-4 py-2 rounded shadow-lg z-50';
            alertDiv.textContent = message;
            
            document.body.appendChild(alertDiv);
            
            // 3秒后移除
            setTimeout(() => {
                alertDiv.style.opacity = '0';
                alertDiv.style.transition = 'opacity 0.5s';
                setTimeout(() => {
                    document.body.removeChild(alertDiv);
                }, 500);
            }, 3000);
        }
    });
</script>
{% endblock %} 